<?php

App::uses('AppController', 'Controller');

/**
 * CakePHP BatchController
 * @author Francis Adu-Gyamfi <francis.adu-gyamfi@matrixdesigns.org>
 */
class BatchController extends AppController {

    public function index() {
        
        if( !$this->request->is('post') ) {
            return $this->_response(array('status' => 'failed', 'message' => 'Invalid request method'));
        }
        
        $data = $this->request->data;
        
        unset($data['APP_ID']);
        unset($data['APP_KEY']);
        unset($data['HTTP_USER_AGENT']);
        unset($data['REMOTE_ADDR']);
        
        $keys = array_keys($data);
        
        if( count($keys) > 5 ) {
            return $this->_response(array('status' => 'failed', 'message' => 'Number of batch requests exceeds limit of 5', 'keys' => $keys));
        }
        
        $response = array();
        
        foreach($data as $key => $obj) {
            $params = isset($obj['params']) ? $obj['params'] : array();
            
            $pass = $obj['method'] == 'post' ? array('data' => $params) : array('url' => $params);
            
            $res = $this->requestAction( $obj['url'], $pass );
            
            try {
                $response[$key] = json_decode($res);
            } catch(Exception $e) {
                $response[$key] = $res;
            }
        }
        
        return $this->_response($response);
    }

}
